//
//  HZMarketViewController.m
//  HZTC_Stock
//
//  Created by MayerF on 17/3/8.
//  Copyright © 2017年 MayerF. All rights reserved.
//

#import "HZMarketViewController.h"
#import "HZHomeView.h"
#import "HZSingleStockViewController.h"
#import "HZSearchViewController.h"
#import "HZStockMoreViewController.h"
#import "HZOwnManagerViewController.h"
#import "QuoteLvOper.h"
#import "HZApiTool.h"
#import "HZPeiziWindow.h"
//#import "CLoginViewController.h"
//#import "ZQHttpManager.h"
//#import "YFLoginRegistViewController.h"
extern QUOTELV_OPER *g_pQuoteOper;

@interface HZMarketViewController ()
{
    int _nOwnId;
    int _nIndexId;
    int _nZhangFuId;
    int _nHuanShouId;
    int _nLiangBiId;
    int _nGaiNianId;
    int _nHangYeId;
    int _nZoneId;
    int _nCYZhangFuId;
    int _nCYHuanShouId;
    int _nCYLiangBiId;
    int _nHKHuGangId;
    int _nHKShenGangId;
    int _nHKHuGuId;
    int _nHKShenGuId;
}
@property (nonatomic, strong)HZHomeView *pHomeView;
@property (nonatomic, strong)UISegmentedControl *pSegmentControl;
@property (nonatomic, strong)UIButton *pLeftBtn;
@property (nonatomic, assign)NSInteger nSegmentIndex;

@property (nonatomic, strong)HZPeiziWindow *pPeiziWindow;
@end

@implementation HZMarketViewController

#pragma mark -
#pragma mark 生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setRightBarBtnItemImage:@"head-search" title:nil];
    
    [self p_loadSegmentedControl];
    _pHomeView = [HZHomeView new];
    _pHomeView.parent = self;
    
    [self.view addSubview:_pHomeView];
    
    [_pHomeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view);
        make.left.mas_equalTo(self.view);
        make.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view);
    }];
    
//    [self setLeftBarBtnItemImage:@"head-edit" title:nil];
    
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:HexAColor(0xFF0000, 1)] forBarMetrics:UIBarMetricsDefault];
    
    
}
- (void)setLeftBarBtnItemImage:(NSString *)imageName title:(NSString *)title
{
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [leftButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [leftButton setTitle:title forState:UIControlStateNormal];
    leftButton.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [leftButton addTarget:self action:@selector(leftBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    _pLeftBtn = leftButton;
    _pLeftBtn.hidden = YES;
}
- (void)leftBtnOnClick {
    HZOwnManagerViewController *pOwnManagerVC = [HZOwnManagerViewController new];
    pOwnManagerVC.parent = self;
    pOwnManagerVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:pOwnManagerVC animated:YES];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    
    if ([HZUserManager manager].isVip && [HZUserManager manager].isNormalShow) {
        [self showPeizi];
        _pPeiziWindow.baseVC = self;
    }
    [self showEdit];
    [self p_subscribeOWnStock];
    [self p_subscribeHuShen];
    [self p_subscribeBlock];
    [self p_subscribeChuangYe];
    [self p_subscribeGangGuTong];
    
    // 如果登录 每次页面显示都拉取自选股
//    if([YFUserModel shareModel].token&&[YFUserModel shareModel].token.length){
        [HZUserManager manager].isLogined = YES;
        [HZUserManager manager].isNormalShow = YES;
//    }
    if ([HZUserManager manager].isNormalShow) {
        [self p_downloadRequest];
    }
}
// 加载配资入口
- (void)showPeizi
{
    if (!_pPeiziWindow) {
        _pPeiziWindow = [[HZPeiziWindow alloc] initWithFrame:CGRectMake(kScreenW-60, kScreenH/2-30, 60, 60)];
//        [[UIApplication sharedApplication].keyWindow addSubview:_pPeiziWindow];
        [HZUserManager manager].peiziWindow = _pPeiziWindow;
    }
    _pPeiziWindow.hidden = NO;
}
- (void)showEdit
{
    _pLeftBtn.hidden = YES;
    if (_nSegmentIndex == 0) {
        if ([HZUserManager manager].isLogined) {
            _pLeftBtn.hidden = NO;
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [HZUserManager manager].peiziWindow.hidden = YES;
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [HZNetworkTool networkCacelSubscribeId:_nOwnId];
    [HZNetworkTool networkCacelSubscribeId:_nIndexId];
    [HZNetworkTool networkCacelSubscribeId:_nZhangFuId];
    [HZNetworkTool networkCacelSubscribeId:_nHuanShouId];
    [HZNetworkTool networkCacelSubscribeId:_nLiangBiId];
    [HZNetworkTool networkCacelSubscribeId:_nGaiNianId];
    [HZNetworkTool networkCacelSubscribeId:_nHangYeId];
    [HZNetworkTool networkCacelSubscribeId:_nZoneId];
    [HZNetworkTool networkCacelSubscribeId:_nCYZhangFuId];
    [HZNetworkTool networkCacelSubscribeId:_nCYHuanShouId];
    [HZNetworkTool networkCacelSubscribeId:_nCYLiangBiId];
    [HZNetworkTool networkCacelSubscribeId:_nHKHuGangId];
    [HZNetworkTool networkCacelSubscribeId:_nHKShenGangId];
    [HZNetworkTool networkCacelSubscribeId:_nHKHuGuId];
    [HZNetworkTool networkCacelSubscribeId:_nHKShenGuId];
    
}

- (void)dealloc{
    NSLog(@"market销毁");
}

#pragma mark -
#pragma mark private
#pragma mark -
#pragma mark ==================订阅==========================
- (void)p_subscribeOWnStock
{
    //避免循环引用
    __weak typeof (self)weakSelf = self;
    
    if ([HZUserManager manager].isLogined) {
        if ([HZUserManager manager].isDownLoadStock) {
            _nOwnId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_Own_Type success:^(id model, kHZApiType apiType) {
                DLog(@"回调结果==%d==%@",apiType,model);
                [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
            }];
        }else {
            [_pHomeView downToChildWithObjc:self withType:KMSClickLoginAndDownLoadOwnStockType withParamter:nil];
            [self p_downloadRequest];
        }
    }else {
        [self.pHomeView downToChildWithObjc:@(kHZApi_Own_Type) withType:kHZ_updateNewData_Action withParamter:@[]];
    }
}
- (void)p_subscribeHuShen
{
    //避免循环引用
    __weak typeof (self)weakSelf = self;
    _nIndexId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_BlockIndex_Type success:^(id model, kHZApiType apiType) {
        [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
    }];
    _nZhangFuId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_ZhangFuTop_Type success:^(id model, kHZApiType apiType) {
        [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
    }];
    _nHuanShouId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_HuanShouTop_Type success:^(id model, kHZApiType apiType) {
        [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
    }];
    _nLiangBiId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_LiangBiTop_Type success:^(id model, kHZApiType apiType) {
        [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
    }];
    
}
- (void)p_subscribeBlock
{
    //避免循环引用
    __weak typeof (self)weakSelf = self;
    _nGaiNianId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_GaiNian_Type success:^(id model, kHZApiType apiType) {
        [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
    }];
    _nHangYeId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_HangYe_Type success:^(id model, kHZApiType apiType) {
        [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
    }];
    _nZoneId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_Zone_Type success:^(id model, kHZApiType apiType) {
        [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
    }];
}
- (void)p_subscribeChuangYe
{
    //避免循环引用
    __weak typeof (self)weakSelf = self;
    _nCYZhangFuId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_ZhangFuTop_CY_Type success:^(id model, kHZApiType apiType) {
        [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
    }];
    _nCYHuanShouId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_HuanShouTop_CY_Type success:^(id model, kHZApiType apiType) {
        [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
    }];
    _nCYLiangBiId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_LiangBiTop_CY_Type success:^(id model, kHZApiType apiType) {
        [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
    }];
}
- (void)p_subscribeGangGuTong
{
    //避免循环引用
    __weak typeof (self)weakSelf = self;
    _nHKHuGangId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_HuGangTong_Type success:^(id model, kHZApiType apiType) {
        [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
    }];
    _nHKShenGangId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_ShenGangTong_Type success:^(id model, kHZApiType apiType) {
        [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
    }];
    _nHKHuGuId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_HuGuTong_Type success:^(id model, kHZApiType apiType) {
        [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
    }];
    _nHKShenGuId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_ShenGuTong_Type success:^(id model, kHZApiType apiType) {
        [weakSelf.pHomeView downToChildWithObjc:[NSNumber numberWithInteger:apiType] withType:kHZ_updateNewData_Action withParamter:model];
    }];
}
#pragma mark -
#pragma mark ==================订阅==========================
- (void)p_loadSegmentedControl
{
//    _pSegmentControl = [[UISegmentedControl alloc] initWithItems:@[@"自选",@"市场"]];
//    _pSegmentControl.selectedSegmentIndex = 0;
//    [_pSegmentControl addTarget:self action:@selector(segmentControlValueChanged:) forControlEvents:UIControlEventValueChanged];
//    UIFont *font = [UIFont boldSystemFontOfSize:15.0f];
//    NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
//    [_pSegmentControl setTitleTextAttributes:attributes forState:UIControlStateNormal];
//    _pSegmentControl.frame = CGRectMake(0, 0, 130, 25);
//    _pSegmentControl.layer.cornerRadius = 5;
//    _pSegmentControl.layer.borderWidth = 1;
//    _pSegmentControl.layer.borderColor = [UIColor whiteColor].CGColor;
//    _pSegmentControl.tintColor = [UIColor whiteColor];
//    _pSegmentControl.layer.masksToBounds = YES;
//    self.navigationItem.titleView = _pSegmentControl;
}

- (void)p_setSegmentState:(NSInteger)index
{
    _pSegmentControl.selectedSegmentIndex = index;
}

- (void)rightBarBtnOnClick{
    [self upToParentWithObjc:self withType:kHZ_presentSearchVC_Action withParamter:nil];
}
#pragma mark -
#pragma mark segmentControl
- (void)segmentControlValueChanged:(UISegmentedControl *)segment
{
    [_pHomeView downToChildWithObjc:self withType:kHZ_segmentControlClick_Action withParamter:segment];
}
// 下载自选股
- (void)p_downloadRequest
{
//    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
//                          @"300032", kAPIFuctionKey,
//                          nil];
//    [HZApiManager apiPostParams:dict success:^(id objc) {
//        if([objc isKindOfClass:[NSArray class]]){
//            [self p_packageOwnedStock:objc];
//        }
//        [HZUserManager manager].isDownLoadStock = YES;
//        [HZNetworkTool networkCacelSubscribeId:_nOwnId];
//        [self p_subscribeOWnStock];
//        [SVProgressHUD dismiss];
//    } failure:^(NSError *error) {
//        [SVProgressHUD showErrorWithStatus:error.domain];
//    }];
    
//    [ZQHttpManager requestPost:kMakeupUrl(BASEURL, @"v3/optionalStock/get") andParam:@{} andSuccess:^(NSDictionary * _Nonnull reslutDic) {
//        NSArray *dataArray = reslutDic[@"data"];
//        if([dataArray isKindOfClass:[NSArray class]]){
//            [self p_packageOwnedStock:dataArray];
//        }
//        [HZUserManager manager].isDownLoadStock = YES;
//        [HZNetworkTool networkCacelSubscribeId:_nOwnId];
//        [self p_subscribeOWnStock];
//        [SVProgressHUD dismiss];
//    } andFailed:^(NSError * _Nullable error, NSDictionary * _Nullable resultDic) {
//
//    }];
}
- (BOOL)checkIsLogined
{
    BOOL isLogined = [HZUserManager manager].isLogined;
    if (!isLogined) {
//        UIViewController *nextVC = [[MYRouter shared] matchController:kRouterLogin];
//        [self.navigationController presentViewController:nextVC animated:YES completion:nil];
    }
    return isLogined;
}
- (void)p_packageOwnedStock:(NSArray *)data
{
    if(!data.count){
//        [CBToast showToastAction:@"暂无自选股！"];
    }
    [HZNetworkTool speicalUpdateOwnStocks:data];
    [HZNetworkTool networkDeleteAllOwnStock];
    NSMutableArray *pTempArray = [NSMutableArray array];
    [data enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *dict = obj;
        NSString *code = nil;
        NSString *market = nil;
        if ([dict.allKeys containsObject:@"code"]) {
            code = dict[@"code"];
        }
        if ([dict.allKeys containsObject:@"market"]) {
            market = dict[@"market"];
        }
        if (code && market) {
            [HZNetworkTool networkAddOwnStock:code WithMarketId:[market integerValue]];
        }
    }];
}
#pragma mark -
- (void)upToParentWithObjc:(id)objc withType:(NSInteger)type withParamter:(id)paramter{
    switch (type) {
        case kHZ_jumpSingleStock_Action:
        {
            HZOwnedStockModel *model = nil;
            if ([paramter isKindOfClass:[HZOwnedStockModel class]]) {
                model = paramter;
            }
            HZSingleStockViewController *pSingleStockVC = [[HZSingleStockViewController alloc] initWithCodeInfo:model];
            pSingleStockVC.parent = self;
            pSingleStockVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:pSingleStockVC animated:YES];
        }
            break;
        case kHZ_setsegmentControlState_Action:
        {
            UIScrollView *pScrollView = (UIScrollView *)paramter;
            _nSegmentIndex = 0;
            if (pScrollView.contentOffset.x <= 0) {
                _nSegmentIndex = 0;
                [self showEdit];
                [self p_setSegmentState:_nSegmentIndex];
            }else if (pScrollView.contentOffset.x >= CGRectGetWidth(self.view.frame)) {
                _nSegmentIndex = 1;
                _pLeftBtn.hidden = YES;
                [self p_setSegmentState:_nSegmentIndex];
            }
        }
            break;
        case kHZ_presentSearchVC_Action:
        {
            HZSearchViewController *pSearchVC = [HZSearchViewController new];
            pSearchVC.parent = self;
            [self presentViewController:pSearchVC animated:YES completion:nil];
        }
            break;
        case kHZ_stockListMore_Action:
        {
            HZStockMoreViewController *pMoreVC = [HZStockMoreViewController new];
            pMoreVC.parent = self;
            [pMoreVC setViewData:(NSString *)paramter];
            pMoreVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:pMoreVC animated:YES];
//            [self presentViewController:pMoreVC animated:YES completion:nil];
        }
            break;
        case kHZ_BlockListDetailClick_Action:
        {
            HZStockMoreViewController *pMoreVC = [HZStockMoreViewController new];
            pMoreVC.parent = self;
            HZOwnedStockModel *model = (HZOwnedStockModel *)paramter;
            [pMoreVC setViewData:model.model_Name];
            pMoreVC.hidesBottomBarWhenPushed = YES;
            [pMoreVC setBlockId:[NSString stringWithFormat:@"%d",model.nModel_BlockId]];
            [self.navigationController pushViewController:pMoreVC animated:YES];
        }
            break;
        case KMSClickLoginAndDownLoadOwnStockType:
        {
            if (![self checkIsLogined]) {
//                if(![YFUserModel shareModel].token||![YFUserModel shareModel].token.length){
//                    CCLoginViewController *yvc = [[CCLoginViewController alloc] init];
//                    [self.navigationController pushViewController:yvc animated:YES];
//                    [yvc ccPushOneStepVC:self];
//                }
                return;
                
            }
        }
            break;
        default:
            break;
    }
}
- (void)downToChildWithObjc:(id)objc withType:(NSInteger)type withParamter:(id)paramter{
}



@end
